package org.seedframework.sharding.resource;


import lombok.extern.slf4j.Slf4j;
import org.seedframework.sharding.springglue.ShardingAutoConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;


@Slf4j
@org.springframework.context.annotation.Configuration
@ConditionalOnSingleCandidate(ShardingAutoConfiguration.class)
@AutoConfigureAfter(ShardingAutoConfiguration.class)
@Import(ShardingDataSourcePoolContext.class)
public class ShardingDataSourceAutoConfiguration implements InitializingBean, ApplicationContextAware {


    private ApplicationContext applicationContext;

    @Bean
    public List<DataSource> dataSources(){
        Collection<ShardingDataSource> shardingDataSources = ShardingDataSourcePoolContext.getShardingDataSource();
        final List<DataSource> rst = new ArrayList<>();
        if(!CollectionUtils.isEmpty(shardingDataSources)){
            shardingDataSources.forEach(o->{
                rst.add(o);
            });
        }
        return rst;
    }

    @Bean
    public DataSource dataSource(){
        if(!CollectionUtils.isEmpty(dataSources())){
            return dataSources().get(0);
        }
        return new ShardingDataSource(null);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
